package com.tuzhi.convert.utils;

import cn.hutool.core.io.FileUtil;
import com.tuzhi.convert.pknuzip.UnPagFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Component
public class ConverterUtils implements InitializingBean {
    static String asm_stp_more_exe;
    static String ugstep214_def_path;
    static String XT_STP_exe;
    static Logger log = LoggerFactory.getLogger(ConverterUtils.class);

    /**
     * prt格式转换命令，ugstep214.def配置文件根路径
     */
    static final String UG_STEP_214_DEF_TYPE = "UG_STEP_214_DEF";
    /**
     * x_t格式执行命令exe文件（XT_STP.exe）根路径
     */
    static final String XT_STP_EXE_TYPE = "XT_STP_EXE";
    /**
     * .prt_.<num>格式执行命令exe文件（ASM_STP_MORE.exe）根路径
     */
    static final String ASM_STEP_MORE_EXE_TYPE = "ASM_STEP_MORE_EXE";
    public static String resourcePath;

    @Value("${convert.filepath.resource_path}")
    private String getResourcePath;

    public static String convertExePath;
    @Value("${convert.filepath.convertExePath}")
    private String getConvertExePath;

    @Override
    public void afterPropertiesSet() throws Exception {
        resourcePath = getResourcePath;
        convertExePath = getConvertExePath;
    }


    /*  static {
          //打包成jar部署后不能这样使用ASM_STP_MORE.exe与XT_STP.exe
          *//*if (StringUtils.isBlank(resource_path)) {
            resource_path = ConverterUtils.class.getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
        }*//*
        resourcePath = "";
        asm_stp_more_exe = resourcePath + "/asm_stp_more/ASM_STP_MORE.exe";
        ugstep214_def_path = "d=" + resourcePath.replaceFirst("/", "") + "x_t_part/ugstep214.def";
        XT_STP_exe = resourcePath.replaceFirst("/", "") + "x_t_part/XT_STP.exe";
    }
*/
    public static String getResourcePath() {
        if (StringUtils.isBlank(resourcePath)) {
            resourcePath = ConverterUtils.class.getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
            resourcePath = resourcePath.replaceFirst("/", "");
        }
        return resourcePath;
    }

    public static String getConvertExePath() {
        if (StringUtils.isBlank(convertExePath)) {
            convertExePath = ConverterUtils.class.getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
            convertExePath = convertExePath.replaceFirst("/", "");
        }
        return convertExePath;
    }

    public static String getExePath(String type) {
        if (UG_STEP_214_DEF_TYPE.equals(type)) {
            if (StringUtils.isBlank(ugstep214_def_path)) {
                ugstep214_def_path = "d=" + Paths.get(getResourcePath(), "x_t_part", "ugstep214.def");
            }
            return ugstep214_def_path;
        }
        if (XT_STP_EXE_TYPE.equals(type)) {
            if (StringUtils.isBlank(XT_STP_exe)) {
                XT_STP_exe = Paths.get(getResourcePath(), "x_t_part", "XT_STP.exe").toString();
            }
            return XT_STP_exe;
        }
        if (ASM_STEP_MORE_EXE_TYPE.equals(type)) {
            if (StringUtils.isBlank(asm_stp_more_exe)) {
                asm_stp_more_exe = Paths.get(getResourcePath(), "asm_stp_more", "ASM_STP_MORE.exe").toString();
            }
            return asm_stp_more_exe;
        }
        return null;
    }

    public static void main(String[] args) throws Exception {

       /* int resultCode = convert4Prt("E:\\tz-java-group-3\\tz-converter-java\\cadFiles\\500053.prt", "E:\\tz-java-group-3\\tz-converter-java\\stepFiles\\555.stp");
        System.out.println("prt result:" + resultCode);*/
//          int resultCode = convert4Prt("D:\\tzconvert\\测试模型\\YH-23110.prt", "D:\\tzconvert\\stepFiles\\555.stp");
//        System.out.println("prt result:" + resultCode);
       /* int resultCode = convert4X_T("E:\\tz-java-group-3\\tz-converter-java\\cadFiles\\1-ASM-230506.x_t", "D:\\tzconvert\\stepFiles\\test555666.stp");
        System.out.println("x_t result:" + resultCode);*/
       /* int resultCode = convert4X_T("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\TY-FW009-6&-7-MP.x_t",
                "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test555666.stp");
        System.out.println("x_t result:" + resultCode);*/

        //有单个asm装配文件有asm配件
       /* int resultCode = convert4zip_rar("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\RJ24-33.rar",
                "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test.stp", "D:\\convert\\unziprar", true);
        System.out.println("convert4zip_rar result:" + resultCode);*/

      /*  int resultCode = convert4zip_rar("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\HC24-5-1B.rar",
                "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test.stp", "D:\\convert\\unziprar", true);
        System.out.println("convert4zip_rar result:" + resultCode);*/

      /*  int resultCode = convert4zip_rar("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\AL00994-PP.zip",
                "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\AL00994-PP.stp", "D:\\convert\\unziprar", true);
        System.out.println("convert4zip_rar result:" + resultCode);*/

        //有单个asm装配文件有asm配件
        /*int resultCode = convert4zip_rar("E:\\tz-java-group-3\\tz-converter-java\\cadFiles\\AL00994-PP-convert.rar",
                "E:\\tz-java-group-3\\tz-converter-java\\stepFiles\\test-rar.stp", "D:\\tzconvert\\unRarZipFiles\\2"
                , true);
        System.out.println("convert4zip_rar result:" + resultCode);*/
       /* int resultCode = convert4zip_rar("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\LEB2024-2699.7z",
                "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test-rar.stp", "D:\\convert\\unziprar"
                , true);
        System.out.println("convert4zip_rar result:" + resultCode);*/
      /*  int resultCode = convert4zip_rar("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\LEB2024-YYB-05-ABS.7z",
                "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test-7z.stp", "D:\\convert\\unziprar"
                , true);
        System.out.println("convert4zip_rar result:" + resultCode);*/

      /*  File unZipRar = UnPagFileUtil.unRarZip7Z("E:\\tz-java-group-3\\tz-converter-java\\cadFiles\\AL00994-PP-convert.rar"
                , "D:\\tzconvert\\unRarZipFiles\\2");
        FileUtil.del(unZipRar);*/


        //zip压缩包,无asm装配文件
      /*  int resultCode = convert4zip_rar("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\jx24-06054-qmk.prt.zip",
                "D:\\my_data\\gitee\\\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test2222.stp", "D:\\convert\\unziprar",true);
        System.out.println("convert4zip_rar result:" + resultCode);*/


//        File unZipRar=new File("D:\\tzconvert\\unRarZipFiles\\2");
////        FileUtil.del(unZipRar);
//        unZipRar.delete();
//        System.out.println(FileUtil.del(unZipRar));

      /*  int resultCode = convert4Prt_num("E:\\tz-java-group-3\\tz-converter-java\\cadFiles\\23-10-227-b.prt.1",
                "E:\\tz-java-group-3\\tz-converter-java\\stepFiles\\test666666888888886.stp");
        System.out.println("convert4zip_rar result:" + resultCode);*/

       /* int resultCode = convert4Prt_num("E:\\tz-java-group-3\\tz-converter-java\\cadFiles\\195qm.prt.1",
                "E:\\tz-java-group-3\\tz-converter-java\\stepFiles\\2.stp");
        System.out.println("convert4zip_rar result:" + resultCode);*/

      /*  int resultCode = convert4Prt("D:\\tzconvert\\cadFiles\\新图  热流道KW7底座B底AS23-001（德信)2.23 (1).prt"
                , "D:\\tzconvert\\stepFiles\\512180888.stp");*/

        int resultCode = convert4New("D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\cadFiles\\LEB2024-YYB-05-ABS.7z", "D:\\my_data\\gitee\\tuzhi-group-3\\tz-converter-java\\stepFiles\\test-7z.stp");
        System.out.println("convert4zip_rar result:" + resultCode);

        System.out.println("prt result:" + resultCode);
    }

    /**
     * 转换 .prt格式文档
     *
     * @param srcPath
     * @param targetPath
     * @return
     */
    public static int convert4Prt(String srcPath, String targetPath) {
        targetPath = "o=" + targetPath;
        return runProcess("cmd", "/c", "step214ug.exe", getExePath(UG_STEP_214_DEF_TYPE), targetPath, srcPath);
    }

    /**
     * 转换 .x_t格式文档
     *
     * @param srcPath
     * @param targetPath
     * @return
     */
    public static int convert4X_T(String srcPath, String targetPath) {
        return runProcess(getExePath(XT_STP_EXE_TYPE), srcPath, targetPath);
    }

    /**
     * 转换 .prt_.<num>格式文档
     *
     * @param srcPath
     * @param targetPath
     * @return
     */
    public static int convert4Prt_num(String srcPath, String targetPath) {
        return runProcess(getExePath(ASM_STEP_MORE_EXE_TYPE), srcPath, targetPath);
    }


    /**
     * 转换 .zip .rar格式文档
     *
     * @param srcPath
     * @param targetPath
     * @return
     */
    public static int convert4zip_rar(String srcPath, String targetPath, String unZipRarPath, boolean deleteFolder) throws Exception {
        String theAsm = null;
        File file = new File(srcPath);
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
//        System.out.println(suffix);
        File unZipRar = UnPagFileUtil.unRarZip7Z(srcPath, unZipRarPath);
        if (unZipRar == null) {
            throw new Exception("未知的文件类型：" + suffix);
        }
        String unZip_Rar_path = unZipRarPath;
        File fileContent = new File(unZipRarPath);
        //获取这个目录下所有的子文件和子目录的数组。
        File[] files = fileContent.listFiles();
        if (files.length == 1 && files[0].isDirectory()) {
            fileContent = new File(files[0].getAbsolutePath());
            unZip_Rar_path = files[0].getAbsolutePath();
            files = fileContent.listFiles();
        }
        String regx = ".*\\.asm(\\.\\d+)?$";
        //遍历这个数组，取出每个File对象
        if (files != null) {
            for (File f : files) {
                //判断这个File是否是一个文件，是：
                if (f.isFile()) {
                    String name = f.getName();
                    if (name.matches(regx)) {
                        theAsm = name;
                    }
                } else {//否则就是一个目录，继续递归
                    //递归调用
                    //System.out.println("这是一个目录");
                }
            }
        }
        int result;
        if (StringUtils.isNotBlank(theAsm)) {
            String asmPath = Paths.get(unZip_Rar_path, theAsm).toString();
            result = runProcess(getExePath(ASM_STEP_MORE_EXE_TYPE), asmPath, targetPath);
        } else {
            List<String> cmds = new ArrayList<>();
            cmds.add(getExePath(ASM_STEP_MORE_EXE_TYPE));
            for (File f : files) {
                cmds.add(Paths.get(unZip_Rar_path, f.getName()).toString());
            }
            cmds.add(targetPath);
            result = runProcess(cmds.toArray(new String[0]));
        }
        if (deleteFolder) {
            FileUtil.del(unZipRar);
        }
        return result;
    }

    /**
     * 转换 .prt/.x_t/.stp等格式文档（除了压缩文件）
     *
     * @param srcPath
     * @param targetPath
     * @return
     */
    public static int convert4New(String srcPath, String targetPath) {
        return runProcess("cmd", "/c", "node", getConvertExePath(), srcPath, targetPath);
    }

    public static int convert4NewOther(String srcPath, String targetPath) {
        //return runProcess("cmd", "/c", "node", getConvertExePath(), srcPath, targetPath);
        try {
            new FileWriter(targetPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return 0;
    }

    /**
     * 运行cmd命令
     *
     * @param cmd
     * @return
     */
    public static int runProcess(String... cmd) {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        // processBuilder.directory(new File("E:\\cmd_dir"));
        Process process = null;
        try {
            process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            return exitCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * 运行cmd命令
     *
     * @param timeoutSeconds 超时时间（单位：秒）
     * @param cmd
     * @return
     */
    public static int runProcess(int timeoutSeconds, String... cmd) {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Process> future = executor.submit(() -> {
            try {
                return processBuilder.start();
            } catch (IOException e) {
                // 处理异常
                e.printStackTrace();
                return null;
            }
        });
        int exitCode = 1;
        try {
            Process process = future.get(timeoutSeconds, TimeUnit.SECONDS);
            // 处理进程输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            exitCode = process.waitFor();
            return exitCode;
        } catch (InterruptedException | ExecutionException | IOException | TimeoutException e) {
            // 超时或执行异常处理
            // 终止进程
            future.cancel(true);
            System.out.println("命令执行超时或执行过程中发生错误");
        } finally {
            executor.shutdownNow(); // 取消执行并关闭线程池
        }
        return exitCode;
    }
}
